package com.bolingcavalry.crm.utils;/*
 * @Auther:Sadie
 * @Date:2025/4/24
 * @Description:
 * @VERSON:1.8
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.base.API;
import com.base.Status;
import com.bolingcavalry.crm.aftersales.mapper.AfterSalesMapper;
import com.bolingcavalry.crm.customer.mapper.CustomerCompaniesMapper;
import com.bolingcavalry.crm.customer.mapper.CustomerContactsMapper;
import com.bolingcavalry.crm.productinstallinfo.mapper.ProductInstallInfoMapper;
import com.bolingcavalry.crm.receiver.mapper.ReceiverMapper;
import com.bolingcavalry.crm.taskorder.mapper.TaskorderMapper;
import com.bolingcavalry.crm.user.mapper.UserMapper;
import com.entity.aftersales.AfterSales;
import com.entity.customer.CustomerCompanies;
import com.entity.customer.CustomerContacts;
import com.entity.product.Product;
import com.entity.taskorder.ProductInstallInfo;
import com.entity.taskorder.TaskOrder;
import com.entity.user.User;
import okhttp3.*;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import com.bolingcavalry.crm.product.mapper.ProductMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class AUtils {
    @Autowired
    private  ProductMapper productMapper;
    @Autowired
    private  UserMapper userMapper;
    @Autowired
    private CustomerCompaniesMapper customerCompaniesMapper;
    @Autowired
    private CustomerContactsMapper customerContactsMapper;
    @Autowired
    private TaskorderMapper taskorderMapper;
    @Autowired
    private ProductInstallInfoMapper productInstallInfoMapper;
    @Autowired
    private AfterSalesMapper afterSalesMapper;
    @Autowired
    private ReceiverMapper receiverMapper;

    /**
     * 根据公司名称获取公司id
     * @param customerCompanyName
     * @return
     */
    public Long getCustomerCompanyId(String customerCompanyName) {
        LambdaQueryWrapper<CustomerCompanies> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerCompanies::getCompanyName, customerCompanyName);
        CustomerCompanies company = customerCompaniesMapper.selectOne(queryWrapper);
        if(company== null){
            return null;
        }

//        if (company == null) {
//            // 公司不存在，创建并插入新公司记录
//            company = new CustomerCompanies();
//            company.setCompanyName(customerCompanyName);
//            // 设置其他字段的默认值（如果有）
//            // company.setOtherField(defaultValue);
//            customerCompaniesMapper.insert(company);
//        }
        return company.getId();
    }

    /**
     * 根据公司名称获取公司id
     * @param customerCompanyName
     * @return
     */
    public Long getCustomerCompanyId(String customerCompanyName,Integer i) {
        LambdaQueryWrapper<CustomerCompanies> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerCompanies::getCompanyName, customerCompanyName);
        CustomerCompanies company = customerCompaniesMapper.selectOne(queryWrapper);
        if(company == null){
            //返回一个null
            return null;
        }
        return company.getId();
    }

    /**
     * 根据公司 ID 获取公司名称
     * @param companyId 公司主键 ID
     * @return 公司名称
     */
    public String getCustomerCompanyNameById(Long companyId) {
        CustomerCompanies company = customerCompaniesMapper.selectById(companyId);
        return company.getCompanyName();
    }

    /**
     * 根据名称获取用户id
     * @param salesManagerName
     * @return
     */
    public  Long getUserIdByNickName(String salesManagerName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getNickname, salesManagerName);
        if(userMapper.selectOne(queryWrapper) == null){
            return null;
        }
        Long id = userMapper.selectOne(queryWrapper).getId();
        return id;
    }
    /**
     * 根据用户 ID 获取用户昵称
     * @param userId 用户主键 ID
     * @return 用户昵称
     */
    public String getUserNickNameByUserId(Long userId) {
        if(userId == null){
            return null;
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            return "";
        }
        return user.getNickname();
    }

    /**
     * 根据产品名称获取产品id
     * @param name
     * @return
     */
    public  Long getProductIdByNameAndSpecification(String name,String specification) {
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Product::getName, name)
                .eq(Product::getSpecification, specification);
        Product select = productMapper.selectOne(queryWrapper);

        if(select == null){
            //新增一个 产品
            Product product = new Product();
            product.setName(name);
            product.setSpecification(specification);
            productMapper.insert(product);
        }
        return select.getId();
    }

    /**
     * 根据联系人信息获取联系人id
     * @param contactPerson
     * @param phoneNumber
     * @param companyId
     * @return
     */
    public Long getcontactPersonId(String contactPerson, String phoneNumber, Long companyId) {
        //先查询姓名+电话是否存在，在查询姓名是否存在，如果姓名电话都存在，就直接返回id
        //如果姓名存在电话不存在就改变电话的值，通知将原来的电话存入json中，然后更新
        LambdaQueryWrapper<CustomerContacts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerContacts::getFullName, contactPerson)
                .eq(CustomerContacts::getPhoneNumber, phoneNumber);
        CustomerContacts existingContact = customerContactsMapper.selectOne(queryWrapper);
        if (existingContact != null) {
            return existingContact.getId(); // 存在则返回已有 ID
        }
//        // 查询仅姓名匹配，则说明手机号码不同
//        LambdaQueryWrapper<CustomerContacts> nameOnlyQuery = new LambdaQueryWrapper<>();
//        nameOnlyQuery.eq(CustomerContacts::getFullName, contactPerson);
//        CustomerContacts nameMatch = customerContactsMapper.selectOne(nameOnlyQuery);
//        if (nameMatch != null) {
//            // 构造历史记录 JSON
//            String oldPhone = nameMatch.getPhoneNumber();
//            String historyJson = buildPhoneHistory(oldPhone, phoneNumber);
//            // 更新电话和历史记录
//            nameMatch.setPhoneNumber(phoneNumber);
//            nameMatch.setHistoryPhone(historyJson);
//            customerContactsMapper.updateById(nameMatch);
//            return nameMatch.getId();
//        }
        //没有则新增
        CustomerContacts newContact = new CustomerContacts();
        newContact.setFullName(contactPerson);      // 姓名
        newContact.setPhoneNumber(phoneNumber);      // 电话
        newContact.setCustomerCompanyId(companyId);  // 关联公司 ID（需传入）
        newContact.setIsPrimary(0);                  // 默认非主要联系人
        newContact.setPosition("");                  // 可选字段初始化为空
        newContact.setEmail("");                     // 可选字段初始化为空
        customerContactsMapper.insert(newContact);
        return newContact.getId(); // 返回新生成的联系人 ID

    }

    //根据联系人姓名获取联系人id
    public Long getcontactPersonId(String contactPerson,String CustomerCompanyName) {
        LambdaQueryWrapper<CustomerContacts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerContacts::getFullName, contactPerson)
                .eq(CustomerContacts::getCustomerCompanyId, getCustomerCompanyId(CustomerCompanyName,1));
        CustomerContacts customerContacts = customerContactsMapper.selectOne(queryWrapper);
        if (customerContacts != null) {
            return customerContacts.getId();
        }
        return null;
    }

    //构建历史手机号记录，传入老的号和最新的号
    private String buildPhoneHistory(String oldPhone, String phoneNumber) {
        return String.format("{\"oldPhone\":\"%s\",\"newPhone\":\"%s\"}", oldPhone, phoneNumber);
    }

    /**
     * 根据联系人 ID 获取联系人姓名
     * @param customerContactsId
     * @return
     */
    public String getContactPersonById(Long customerContactsId) {
        CustomerContacts customerContacts = customerContactsMapper.selectById(customerContactsId);
        if (customerContacts == null) {
            return null;
        }
        return customerContacts.getFullName();
    }

    /**
     * 根据联系人 ID 获取联系人电话
     * @param customerContactsId
     * @return
     */
    public String getPhoneNumberById(Long customerContactsId) {
        CustomerContacts customerContacts = customerContactsMapper.selectById(customerContactsId);
        if (customerContacts == null) {
            throw new RuntimeException("未找到对应联系人信息");
        }
        return customerContacts.getPhoneNumber();
    }
    /**
     * 根据联系人登录名获取联系人姓名
     */
    public String getNickNameByuserName(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        return userMapper.selectOne(queryWrapper).getNickname();
    }

    /**
     * 获取文件base64编码
     * 同时压缩图片
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    public static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        File file = new File(path);

        // 判断文件大小是否超过 1MB
        boolean needCompress = file.length() > 1048576; // 1MB = 1024 * 1024 bytes
        ByteArrayOutputStream baos;

        // 读取原始图片
        BufferedImage image = ImageIO.read(new File(path));

        if (needCompress) {
            // 设置目标尺寸（根据接口要求调整）
            int targetWidth = 1024;
            int targetHeight = (int) (((double) targetWidth / image.getWidth()) * image.getHeight());


            // 缩放图片
            Image scaledImage = image.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
            BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = outputImage.createGraphics();
            g.drawImage(scaledImage, 0, 0, null);
            g.dispose();

            // 写入临时字节数组
            baos = new ByteArrayOutputStream();
            ImageIO.write(outputImage, "jpg", baos);

            // 【新增】将压缩后的图片写入本地文件，方便查看
            String outputPath = "C:/Users/Sadie/Desktop/compressed_image.jpg"; // 你可以自定义路径
            try (FileOutputStream fos = new FileOutputStream(outputPath)) {
                fos.write(baos.toByteArray());
            }
            System.out.println("压缩后的图片已保存至：" + outputPath);

        } else {
            // 不需要压缩，直接读取原图内容
            baos = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", baos);
        }

        byte[] bytes = baos.toByteArray();

        // Base64 编码
        String base64 = Base64.getEncoder().encodeToString(bytes);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }

    /**
     * 将 MultipartFile 转换为 Base64 编码
     * @param file
     * @param urlEncode
     * @return
     * @throws IOException
     */
    public static String getFileContentAsBase64(MultipartFile file, boolean urlEncode) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("上传的图片不能为空");
        }

        // 获取原始图片格式（png/jpg等）
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new IllegalArgumentException("文件名为空");
        }
        String formatName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

        // 读取图片
        BufferedImage image = ImageIO.read(file.getInputStream());

        // 判断是否需要压缩
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        boolean needCompress = file.getSize() > 1048576; // 大于 1MB 需要压缩

        if (needCompress) {
            int targetWidth = 1024;
            int targetHeight = (int) (((double) targetWidth / image.getWidth()) * image.getHeight());

            Image scaledImage = image.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
            BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = outputImage.createGraphics();
            g.drawImage(scaledImage, 0, 0, null);
            g.dispose();

            ImageIO.write(outputImage, "jpg", baos); // 输出为 jpg 格式
        } else {
            ImageIO.write(image, formatName, baos); // 保留原格式
        }

        byte[] bytes = baos.toByteArray();
        String base64 = Base64.getEncoder().encodeToString(bytes);

        if (urlEncode) {
            base64 = java.net.URLEncoder.encode(base64, "utf-8");
        }

        return base64;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().readTimeout(300, TimeUnit.SECONDS).build();
    public static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API.API_KEY
                + "&client_secret=" + API.SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

    /**
     *根据服务单号获取任务单ID
     * @param serviceNumber
     * @return
     */
    public Long getTaskOrderIdByServiceNumber(String serviceNumber) {
        LambdaQueryWrapper<TaskOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TaskOrder::getTaskOrderNumber, serviceNumber)
                .eq(TaskOrder::getIsDeleted, 1);
        TaskOrder taskOrder = taskorderMapper.selectOne(queryWrapper);
        if (taskOrder == null) {
            return null;
        }
        return taskOrder.getId();
    }
    //根据售后总括表id获取售后单号
    public String getAfterSalesNumberById(Long afterSalesId) {
        LambdaQueryWrapper<AfterSales> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AfterSales::getId, afterSalesId);
        AfterSales afterSales = afterSalesMapper.selectOne(queryWrapper);
        if (afterSales == null) {
            return null;
        }
        return afterSales.getOrderNumber();
    }

    /**
     * 根据任务单id获取产品安装信息id
     * @param id
     * @return
     */
    public Long getProductInstallInfoIdByTaskOrderId(Long id) {
        LambdaQueryWrapper<ProductInstallInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductInstallInfo::getTaskOrderId, id);
        ProductInstallInfo productInstallInfo = productInstallInfoMapper.selectOne(queryWrapper);
        if (productInstallInfo == null) {
            return null;
        }
        return productInstallInfo.getId();
    }

    //根据传入的userid查询该用户对应的角色
    public List<String> getRoleByUserId(Long receiverId) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, receiverId);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return null;
        }
        return userMapper.getRoleByNickname(user.getUsername());
    }

    //根据传入的名称查询该用户对应的角色
    public List<String> getRoleByUserName(String receiverName) {
        return userMapper.getRoleByNickname(receiverName);
    }

    //判断是否为null和空字符串，为null则返回null，不为null则返回对应的值
    public static String getString(JSONObject obj, String key) {
            if (obj == null || obj.isNull(key)) {
                return null;
            }
            String value = obj.optString(key).trim();
            return value.isEmpty() ? null : value;
    }


    //根据售后单号获取售后总括单ID
    public Long getAfterSalesId(String afterSalesId) {
        LambdaQueryWrapper<AfterSales> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AfterSales::getOrderNumber, afterSalesId);
        AfterSales afterSales = afterSalesMapper.selectOne(queryWrapper);
        return afterSales == null ? null : afterSales.getId();
    }

    /**
     * 根据nickname列表获取对应的userId列表
     * @param receiverName
     * @return
     */
    public List<Long> getUserIdsByNickName(List<String> receiverName) {
        return userMapper.getUserIdsByNickName(receiverName);
    }

    /**
     * 根据输入的nickname模糊匹配获取对应的userId列表
     * @param receiverName
     * @return
     */

    public List<Long> getUserIdsByNamemohu(String receiverName) {
        return userMapper.getUserIdsByNamemohu(receiverName);
    }

    /**
     * 根据接收人id列表获取对应的nickname列表
     */
    public List<String> getUserNamesByUserIds(List<Long> receiverId) {
        return userMapper.getUserNamesByUserId(receiverId);
    }

    /**
     * 根据userId获取对应的username
     * @param userId
     * @return
     */
    public String getUserNameByUserId(Long userId) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, userId);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return null;
        }
        return user.getUsername();
    }

    /**
     * 根据roleId获取对应的userId列表
     * @param RoleId
     * @return
     */
    public List<Long> getUserIdsByRoleId(Long RoleId) {
        return userMapper.getUserIdsByRoleId(RoleId);
    }
    /**
     * 根据角色名获取对应的userId列表
     */
    public List<Long> getUserIdsByRoleName(String roleName) {
        return userMapper.getUserIdsByRoleName(roleName);
    }

    /**
     * 根据角色名查询角色id
     */
    public Long getRoleIdByRoleName(String roleName) {
        return userMapper.getRoleIdByRoleName(roleName);
    }

    public Long getUserIdByUserName(String currentUsername) {
        return userMapper.getUserIdByUserName(currentUsername);
    }


    public int getOrderCount(String taskOrderNumber) {
        return taskorderMapper.getOrderCount(taskOrderNumber);
    }
    //根据业务类型获取对应的业务类型名称
    public String getBusinessTypename(String businessType) {
        //确认单
        if(Status.CONFIRMATION_ORDER.equals(businessType)){
            return Status.CONFIRMATION_ORDER_CN;
        }
        //服务单
        if(Status.SERVICE_ORDER.equals(businessType)){
            return Status.SERVICE_ORDER_CN;
        }
        //总结单
        if(Status.SUMMARY_ORDER.equals(businessType)){
            return Status.SUMMARY_ORDER_CN;
        }
        //服务问题
        if(Status.SERVICE_PROBLEM.equals(businessType)){
            return Status.SERVICE_PROBLEM_CN;
        }
        if (Status.TASK_ORDER.equals(businessType)){
            return Status.TASK_ORDER_CN;
        }
        return null;
    }

    /**
     * 根据售后编号更新售后单的更新时间
     * @param serviceOrderNumber
     */
    public void updateServiceOrderUpdateTime(String serviceOrderNumber) {
        LambdaQueryWrapper<AfterSales> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AfterSales::getOrderNumber, serviceOrderNumber);
        AfterSales afterSales = afterSalesMapper.selectOne(queryWrapper);
        if(afterSales!=null){
            afterSales.setUpdateTime(LocalDateTime.now());
            afterSalesMapper.update(afterSales, queryWrapper);
        }
    }

    public List<String> getUserNickNamesByIds(List<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) return Collections.emptyList();
        List<User> users = userMapper.selectBatchIds(userIds);
        return users.stream().map(User::getNickname).collect(Collectors.toList());
    }

    //根据售后单号查询售后id
    public Long getAfterSalesIdByNumber(Long ordernumber) {
        return afterSalesMapper.getAfterSalesIdByNumber(ordernumber);
    }

//    public Double getServiceDays(LocalDateTime startTime, LocalDateTime endTime) {
//
//    }
}
